<?php

namespace app\index\controller;

use app\index\BaseController;
use app\common\model\NoticeMessage;

class MessagesNotice extends BaseController
{
    /**
     * 获取所有公告
     *
     * @return \think\Response
     */
    public function getAllNoticeMessages()
    {
        return json(
            NoticeMessage::where(1)->order('update_at desc')->select()
        );
    }

    /**
     * 发表公告
     *
     * @return \think\Response
     * @args content 公告内容
     */
    public function createNoticeMessage()
    {
        $content = input('content') ?: error('公告不能为空');

        $message = new NoticeMessage();
        $message->content = $content;
        $message->save();

        return json([
            'message' => '发表成功'
        ]);
    }

    /**
     * 编辑公告
     *
     * @return \think\Response
     * @args id 公告ID
     * @args content 公告内容
     */
    public function editNoticeMessage($id)
    {
        $content = input('content') ?: error('公告不能为空');

        /** @var NoticeMessage $message */
        $message = NoticeMessage::where('id', $id)->find();
        if (!$message) {
            error('公告不存在');
        }

        $message->content = $content;
        $message->save();

        return json([
            'message' => '编辑成功'
        ]);
    }

    /**
     * 删除公告
     *
     * @return \think\Response
     * @args id ID
     */
    public function removeNoticeMessage($id)
    {
        /** @var NoticeMessage $message */
        $message = NoticeMessage::where('id', $id)->find();
        if (!$message) {
            error('公告不存在');
        }

        $message->delete();

        return json([
            'message' => '删除成功'
        ]);
    }
}
